<script setup>
import { ref } from 'vue'
import StepProgress from './StepProgress.vue'
import request from '@/utils/request'
import axios from 'axios'

const steps = ['填写身份证', '录制视频', '验证结果']
const name = ref('')
const id = ref('')
const idFront = ref('')
const idBack = ref('')
const idFrontUrl = ref('')
const idBackUrl = ref('')
const fileInputFront = ref(null)
const fileInputBack = ref(null)
const loading = ref(false)
const ocrError = ref('')
const emit = defineEmits(['next'])
const frontFile = ref(null)
const backFile = ref(null)

function upload(type) {
  if (type === 'front') {
    fileInputFront.value && fileInputFront.value.click()
  } else {
    fileInputBack.value && fileInputBack.value.click()
  }
}

async function onFileChange(e, type) {
  const file = e.target.files[0]
  if (!file) return
  
  // 文件大小检查
  if (file.size > 10 * 1024 * 1024) {
    alert('图片大小不能超过10MB')
    return
  }
  
  const formData = new FormData()
  formData.append('image', file)
  loading.value = true
  ocrError.value = ''
  
  try {
    console.log('开始上传图片:', file.name, '大小:', file.size)
    const res = await request.post('user/id-card/ocr/', formData)
    // 自动调试打印后端返回内容和类型
    console.log('后端返回内容(axios):', res.data);
    console.log('后端返回类型(axios):', typeof res.data);
    
    // 放宽判断条件，只要返回了数据就尝试处理
    if (res.data && (res.data.words_list || res.data.success !== false)) {
      if (type === 'front') {
        idFront.value = URL.createObjectURL(file)
        frontFile.value = file
        idFrontUrl.value = res.data.path || ''
        
        // 如果有 words_list 就尝试识别
        if (res.data.words_list && Array.isArray(res.data.words_list)) {
          const words = res.data.words_list
          console.log('识别到的文字:', words)
          
          const nameItem = words.find(w => w.replace(/\s/g, '').startsWith('姓名'))
          const idItem = words.find(w => /\d{15,18}/.test(w))
          
          if (nameItem) {
            name.value = nameItem.replace(/姓名[:：\s]*/, '').trim()
            console.log('识别到姓名:', name.value)
          }
          if (idItem) {
            id.value = idItem.match(/\d{15,18}/)[0]
            console.log('识别到身份证号:', id.value)
          }
          
          if (!name.value || !id.value) {
            ocrError.value = '未能自动识别出姓名或身份证号，请手动填写。'
          }
        } else {
          ocrError.value = '图片上传成功，但未能识别文字，请手动填写信息。'
        }
      } else {
        idBack.value = URL.createObjectURL(file)
        backFile.value = file
        idBackUrl.value = res.data.path || ''
        console.log('身份证反面上传成功')
      }
    } else {
      const errorMsg = res.data?.message || res.data?.msg || '上传失败，请重试'
      ocrError.value = errorMsg
      console.error('上传失败:', res.data)
    }
  } catch (e) {
    console.error('上传异常:', e)
    const errorMsg = e.response?.data?.msg || e.response?.data?.message || e.message || '网络错误'
    ocrError.value = '图片上传失败：' + errorMsg
    alert('图片上传失败：' + errorMsg)
  } finally {
    loading.value = false
  }
}

async function submit() {
  // 校验姓名
  if (!name.value.trim()) {
    alert('请输入姓名')
    return
  }
  // 校验身份证号（15位或18位数字，或17位数字+X/x）
  const idPattern = /^(\d{15}|\d{17}[\dXx])$/
  if (!idPattern.test(id.value.trim())) {
    alert('请输入正确的身份证号')
    return
  }
  if (!frontFile.value || !backFile.value) {
    alert('请上传身份证并确保信息完整')
    return
  }
  // 上传身份证图片时带上 user_id，接口为 /user/upload/id-card/
  const userId = localStorage.getItem('userid') || '1'
  const formData = new FormData()
  formData.append('front_image', frontFile.value)
  formData.append('back_image', backFile.value)
  formData.append('user_id', userId)
  try {
    const res = await axios.post('http://localhost:8000/user/upload/id-card/', formData)
    // 优先判断 code 字段
    const s = res.data.success;
    if ((res.data.code && res.data.code === 200) || s === true || s === 'true' || s === 'True' || s === 1 || s === '1') {
      alert('身份证图片上传成功！')
      emit('next', {
        name: name.value,
        id: id.value,
        idFrontUrl: res.data.front_url || '',
        idBackUrl: res.data.back_url || ''
      })
    } else {
      alert('身份证图片上传失败：' + (res.data.msg || '未知错误'))
    }
  } catch (err) {
    alert('身份证图片上传接口异常')
  }
}

function getFullImageUrl(url) {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return 'http://127.0.0.1:8000' + url
}
</script>

<template>
  <div class="idcard-container">
    <h2 class="title">身份认证</h2>
    <div class="step-bar">
      <span v-for="(step, idx) in steps" :key="step" :class="['step', {active: idx === 0}]">
        {{ step }}
        <span v-if="idx < steps.length - 1" class="divider">→</span>
      </span>
    </div>
    <div class="form-area">
      <div class="upload-row">
        <div class="upload-box" @click="upload('front')">
          <span v-if="!idFront">点击上传身份证正面</span>
          <img v-else :src="idFront" alt="身份证正面" />
        </div>
        <div class="upload-box" @click="upload('back')">
          <span v-if="!idBack">点击上传身份证反面</span>
          <img v-else :src="idBack" alt="身份证反面" />
        </div>
      </div>
      <div class="input-row">
        <input v-model="name" placeholder="姓名" class="input" />
        <input v-model="id" placeholder="身份证号" class="input" />
      </div>
      <div class="tip-text">请确保身份证边框完整，文字清晰可见</div>
      <div v-if="ocrError" class="ocr-error">{{ ocrError }}</div>
      <button class="next-btn" @click="submit" :disabled="loading">{{ loading ? '识别中...' : '下一步：录制视频' }}</button>
      <input ref="fileInputFront" type="file" accept="image/*" style="display:none" @change="e => onFileChange(e, 'front')" />
      <input ref="fileInputBack" type="file" accept="image/*" style="display:none" @change="e => onFileChange(e, 'back')" />
    </div>
  </div>
</template>

<style scoped>
.idcard-container {
  max-width: 420px;
  margin: 60px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px #e6eaf1;
  padding: 32px 32px 28px 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title {
  font-size: 26px;
  font-weight: bold;
  color: #222;
  margin-bottom: 24px;
  letter-spacing: 2px;
}
.step-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 28px;
  width: 100%;
}
.step {
  color: #5bb6e7;
  font-size: 18px;
  font-weight: 500;
  padding: 0 2px;
  transition: color 0.2s;
}
.step.active {
  color: #2196f3;
  font-weight: bold;
  border-bottom: 2px solid #2196f3;
}
.divider {
  margin: 0 16px;
  color: #bbb;
  font-size: 18px;
  font-weight: 300;
}
.form-area {
  width: 100%;
}
.upload-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 18px;
}
.upload-box {
  width: 48%;
  height: 90px;
  border: 2px dashed #c8d6e8;
  border-radius: 8px;
  color: #b0b8c7;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 15px;
  background: #f8fafc;
  cursor: pointer;
  transition: border-color 0.2s, color 0.2s;
  overflow: hidden;
}
.upload-box:hover {
  border-color: #2196f3;
  color: #2196f3;
}
.upload-box img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 6px;
}
.input-row {
  display: flex;
  gap: 12px;
  margin-bottom: 14px;
}
.input {
  flex: 1;
  height: 38px;
  border: 1px solid #e0e6ed;
  border-radius: 6px;
  padding: 0 12px;
  font-size: 15px;
  outline: none;
  transition: border-color 0.2s;
}
.input:focus {
  border-color: #2196f3;
}
.tip-text {
  background: #f3f6fa;
  color: #b0b8c7;
  font-size: 14px;
  border-radius: 6px;
  padding: 8px 0;
  text-align: center;
  margin-bottom: 18px;
}
.next-btn {
  width: 100%;
  height: 42px;
  background: #2196f3;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 17px;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.2s;
  margin-top: 6px;
}
.next-btn:hover {
  background: #1976d2;
}
.ocr-error {
  color: #e53935;
  background: #fff0f0;
  border-radius: 6px;
  padding: 6px 0;
  text-align: center;
  margin-bottom: 10px;
  font-size: 14px;
}
</style>